package com.ffggffgfv.backend.controller;

import com.ffggffgfv.backend.dto.CartDisplayDTO;
import com.ffggffgfv.backend.dto.CartItemDTO;
import com.ffggffgfv.backend.entity.Cart;
import com.ffggffgfv.backend.service.CartService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 获取购物车列表
     *
     * @param token JWT令牌
     * @return 购物车项列表
     */
    @GetMapping("/list")
    public Result getCartList(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        List<CartDisplayDTO> cartList = cartService.getCartList(userId);
        return Result.success(cartList, "获取购物车列表成功");
    }

    /**
     * 添加商品到购物车
     *
     * @param cartItemDTO 购物车项信息
     * @param token       JWT令牌
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result addToCart(@RequestBody CartItemDTO cartItemDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数校验
        if (cartItemDTO.getProductId() == null) {
            return Result.validateFailed("商品ID不能为空");
        }
        if (cartItemDTO.getQuantity() == null || cartItemDTO.getQuantity() <= 0) {
            return Result.validateFailed("商品数量必须大于0");
        }

        Cart cart = cartService.addToCart(userId, cartItemDTO);
        if (cart == null) {
            return Result.validateFailed("添加失败，商品可能不存在或已下架");
        }

        return Result.success(cart, "添加到购物车成功");
    }

    /**
     * 更新购物车项
     *
     * @param cartItemDTO 购物车项信息
     * @param token       JWT令牌
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result updateCart(@RequestBody CartItemDTO cartItemDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数校验
        if (cartItemDTO.getProductId() == null) {
            return Result.validateFailed("商品ID不能为空");
        }

        Cart cart = cartService.updateCart(userId, cartItemDTO);
        if (cart == null) {
            return Result.validateFailed("更新失败，购物车中可能不存在该商品");
        }

        return Result.success(cart, "更新购物车成功");
    }

    /**
     * 删除购物车项
     *
     * @param productId 商品ID
     * @param token     JWT令牌
     * @return 删除结果
     */
    @DeleteMapping("/delete/{productId}")
    public Result deleteCartItem(@PathVariable Long productId, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        int result = cartService.deleteCartItem(userId, productId);
        if (result > 0) {
            return Result.success(null, "删除购物车商品成功");
        } else {
            return Result.validateFailed("删除失败，购物车中可能不存在该商品");
        }
    }

    /**
     * 清空购物车
     *
     * @param token JWT令牌
     * @return 清空结果
     */
    @DeleteMapping("/clear")
    public Result clearCart(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        int result = cartService.clearCart(userId);
        return Result.success(result, "清空购物车成功");
    }

    /**
     * 切换商品选中状态
     *
     * @param productId 商品ID
     * @param selected  选中状态
     * @param token     JWT令牌
     * @return 切换结果
     */
    @PutMapping("/toggle-select")
    public Result toggleSelected(@RequestParam Long productId,
                                 @RequestParam Boolean selected,
                                 @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        int result = cartService.toggleSelected(userId, productId, selected);
        if (result > 0) {
            return Result.success(null, "更新选中状态成功");
        } else {
            return Result.validateFailed("更新失败，购物车中可能不存在该商品");
        }
    }

    /**
     * 全选/全不选
     *
     * @param selected 选中状态
     * @param token    JWT令牌
     * @return 切换结果
     */
    @PutMapping("/toggle-all-select")
    public Result toggleAllSelected(@RequestParam Boolean selected, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        int result = cartService.toggleAllSelected(userId, selected);
        return Result.success(result, "更新全部选中状态成功");
    }

    /**
     * 获取购物车商品数量
     *
     * @param token JWT令牌
     * @return 商品数量
     */
    @GetMapping("/count")
    public Result getCartProductCount(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        int count = cartService.getCartProductCount(userId);
        return Result.success(count, "获取购物车商品数量成功");
    }

    /**
     * 获取选中的购物车项，用于结算
     *
     * @param token JWT令牌
     * @return 选中的购物车项
     */
    @GetMapping("/selected")
    public Result getSelectedCartItems(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        Map<String, Object> result = cartService.getSelectedCartItems(userId);
        return Result.success(result, "获取选中的购物车商品成功");
    }

    /**
     * 从令牌中提取用户ID
     *
     * @param token JWT令牌
     * @return 用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                return jwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
